import {
	createStore
} from 'vuex'
import createPersistedState from "vuex-persistedstate";
import {
	getUserRole
} from '@/api/index';

export default createStore({
	state: {
		tagsList: [],
		collapse: true,
		adminMsg: {},
		permissions: []
	},
	mutations: {
		getAdminMsg(state, data) {
			state.adminMsg = data
		},
		clearAdminMsg(state) {
			state.adminMsg = {}
		},
		setPermissions(state, data) {
			state.permissions = data
		},
		delTagsItem(state, data) {
			state.tagsList.splice(data.index, 1);
		},
		setTagsItem(state, data) {
			state.tagsList.push(data)
		},
		clearTags(state) {
			state.tagsList = []
		},
		closeTagsOther(state, data) {
			state.tagsList = data;
		},
		closeCurrentTag(state, data) {
			for (let i = 0, len = state.tagsList.length; i < len; i++) {
				const item = state.tagsList[i];
				if (item.path === data.$route.fullPath) {
					if (i < len - 1) {
						data
							.$router
							.push(state.tagsList[i + 1].path);
					} else if (i > 0) {
						data
							.$router
							.push(state.tagsList[i - 1].path);
					} else {
						data
							.$router
							.push("/");
					}
					state
						.tagsList
						.splice(i, 1);
					break;
				}
			}
		},
		// 侧边栏折叠
		hadndleCollapse(state, data) {
			state.collapse = data;
		}
	},
	actions: {
		async getPermissions({
			state,
			commit
		}) {
			let permissions=[]

			// 调用getUserRole接口获取权限数据
			const res = await getUserRole({
				id: state.adminMsg.id || ''
			});

			if (res.code === 2000) {
				// 解析权限数据
				permissions = res.data ? JSON.parse(res.data) : [];

				// 提交mutation保存到state
			}
			commit('setPermissions', permissions);
			return Promise.resolve(permissions);
				
		}
	},
	modules: {},
	plugins: [createPersistedState({
		reducer: (state) => {
			const {
				permissions,
				...persistedState
			} = state
			return persistedState
		}
	})],
})